package com.jxb.lession78.web.servlet;

import com.jxb.lession78.common.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String method = req.getParameter("method");
            Class<? extends BaseController> aClass = this.getClass();
            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            String result = (String) method1.invoke(this, req, resp);
            if (result != null) {
                if (result.contains(Constant.FORWARD)) {
                    System.out.println("这是转发");
                    req.getRequestDispatcher(result.replace(Constant.FORWARD,"")).forward(req,resp);
                } else if (result.contains(Constant.REDIRECT)) {
                    System.out.println("这是重定向");
                    resp.sendRedirect(result.replace(Constant.REDIRECT,""));
                } else {
                    System.out.println("这是写出");
                    resp.getWriter().println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
